// MCP API 测试脚本
import http from 'http';

const API_BASE = 'http://localhost:3000/api/v1';

/**
 * 发送HTTP请求
 */
function makeRequest(path, options = {}) {
  return new Promise((resolve, reject) => {
    const url = new URL(path, API_BASE);
    const requestOptions = {
      hostname: url.hostname,
      port: url.port,
      path: url.pathname + url.search,
      method: options.method || 'GET',
      headers: {
        'Content-Type': 'application/json',
        'User-Agent': 'MCP-Test-Client/1.0',
        ...options.headers
      }
    };

    const req = http.request(requestOptions, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const parsedData = data ? JSON.parse(data) : {};
          resolve({
            statusCode: res.statusCode,
            headers: res.headers,
            data: parsedData
          });
        } catch (error) {
          resolve({
            statusCode: res.statusCode,
            headers: res.headers,
            data: data
          });
        }
      });
    });

    req.on('error', reject);

    if (options.body) {
      req.write(JSON.stringify(options.body));
    }

    req.end();
  });
}

/**
 * 测试健康检查
 */
async function testHealthCheck() {
  console.log('🩺 测试健康检查...');
  
  try {
    const response = await makeRequest('/health');
    console.log(`状态码: ${response.statusCode}`);
    console.log('响应:', JSON.stringify(response.data, null, 2));
    return response.statusCode === 200;
  } catch (error) {
    console.error('健康检查失败:', error.message);
    return false;
  }
}

/**
 * 测试发送消息
 */
async function testSendMessage() {
  console.log('📨 测试发送消息...');
  
  const testMessage = {
    type: 'user.message',
    payload: {
      content: '这是一条测试消息',
      userId: 'test-user-123',
      timestamp: new Date().toISOString()
    },
    source: 'test-client',
    priority: 'medium',
    headers: {
      'x-test-id': 'msg-001',
      'x-client-version': '1.0.0'
    }
  };

  try {
    const response = await makeRequest('/messages', {
      method: 'POST',
      body: testMessage
    });

    console.log(`状态码: ${response.statusCode}`);
    console.log('响应:', JSON.stringify(response.data, null, 2));
    
    if (response.statusCode === 202 && response.data.success) {
      console.log('✅ 消息发送成功');
      return response.data.data.messageId;
    } else {
      console.log('❌ 消息发送失败');
      return null;
    }
  } catch (error) {
    console.error('发送消息失败:', error.message);
    return null;
  }
}

/**
 * 测试批量发送消息
 */
async function testBatchMessages() {
  console.log('📦 测试批量发送消息...');
  
  const batchMessages = {
    messages: [
      {
        type: 'user.message',
        payload: {
          content: '批量消息 #1',
          userId: 'batch-user-001'
        },
        source: 'batch-test',
        priority: 'high'
      },
      {
        type: 'system.notification',
        payload: {
          title: '系统通知',
          message: '这是一个批量系统通知',
          level: 'info'
        },
        source: 'system',
        priority: 'low'
      },
      {
        type: 'ai.request',
        payload: {
          prompt: '请解释MCP系统的工作原理',
          model: 'test-model',
          requiresResponse: true
        },
        source: 'ai-client',
        priority: 'critical'
      }
    ]
  };

  try {
    const response = await makeRequest('/messages/batch', {
      method: 'POST',
      body: batchMessages
    });

    console.log(`状态码: ${response.statusCode}`);
    console.log('响应:', JSON.stringify(response.data, null, 2));
    
    if (response.statusCode === 202 && response.data.success) {
      const { accepted, rejected } = response.data.data;
      console.log(`✅ 批量处理完成: ${accepted}条接受, ${rejected}条拒绝`);
      return true;
    } else {
      console.log('❌ 批量消息处理失败');
      return false;
    }
  } catch (error) {
    console.error('批量发送消息失败:', error.message);
    return false;
  }
}

/**
 * 测试无效消息
 */
async function testInvalidMessage() {
  console.log('❌ 测试无效消息...');
  
  const invalidMessage = {
    type: '', // 无效的空类型
    payload: null, // 无效的null载荷
    // 缺少必需字段
  };

  try {
    const response = await makeRequest('/messages', {
      method: 'POST',
      body: invalidMessage
    });

    console.log(`状态码: ${response.statusCode}`);
    console.log('错误响应:', JSON.stringify(response.data, null, 2));
    
    if (response.statusCode === 400 && !response.data.success) {
      console.log('✅ 正确处理了无效消息');
      return true;
    } else {
      console.log('❌ 无效消息处理异常');
      return false;
    }
  } catch (error) {
    console.error('测试无效消息失败:', error.message);
    return false;
  }
}

/**
 * 测试消息查询
 */
async function testMessageQuery() {
  console.log('🔍 测试消息查询...');
  
  try {
    const response = await makeRequest('/messages?page=1&limit=10&type=user.message');

    console.log(`状态码: ${response.statusCode}`);
    console.log('响应:', JSON.stringify(response.data, null, 2));
    
    if (response.statusCode === 200 && response.data.success) {
      console.log('✅ 消息查询成功');
      return true;
    } else {
      console.log('❌ 消息查询失败');
      return false;
    }
  } catch (error) {
    console.error('消息查询失败:', error.message);
    return false;
  }
}

/**
 * 主测试函数
 */
async function runTests() {
  console.log('🚀 开始 MCP API 测试...\n');
  
  const tests = [
    { name: '健康检查', fn: testHealthCheck },
    { name: '发送消息', fn: testSendMessage },
    { name: '批量发送消息', fn: testBatchMessages },
    { name: '无效消息处理', fn: testInvalidMessage },
    { name: '消息查询', fn: testMessageQuery }
  ];

  let passed = 0;
  let failed = 0;

  for (const test of tests) {
    console.log(`\n--- ${test.name} ---`);
    try {
      const result = await test.fn();
      if (result) {
        passed++;
        console.log(`✅ ${test.name} 通过`);
      } else {
        failed++;
        console.log(`❌ ${test.name} 失败`);
      }
    } catch (error) {
      failed++;
      console.log(`❌ ${test.name} 出错: ${error.message}`);
    }
  }

  console.log(`\n📊 测试结果: ${passed}/${tests.length} 通过`);
  
  if (failed === 0) {
    console.log('🎉 所有测试都通过了！');
    process.exit(0);
  } else {
    console.log(`⚠️  ${failed} 个测试失败`);
    process.exit(1);
  }
}

// 等待一些时间让服务器启动
console.log('⏳ 等待服务器启动...');
setTimeout(runTests, 3000);
